import { getEnv, getUrlParam, getQuery } from './util';
import { Toast, Dialog } from 'vant';
import {ifUserMock, userMock} from './config'

let global_userInfo = null;
let miniData = {
  param: {},
  store: [],
  isJumping: false
}

export const setUserInfo = (val) => {
  global_userInfo = val;
  // if(isCBD)global_userInfo = {memberId: val}
  // else if(isWX)global_userInfo = {sessionCode: val}
};

export const getUserInfo = () => {
  return global_userInfo;
};

//miniJumpAddress： 微信小程序登录之后跳转的地址，不传默认为当前地址
export const wxMiniLogin = (miniJumpAddress) => {
  return new Promise((resolve, reject) => {
    let query = getQuery();
    if(query.__isPageShow){
      miniData.store.push([resolve, reject])
      if(!miniData.isJumping){
        miniData.isJumping = true;
        wx.miniProgram.navigateTo({
          url: `/pages/common/mobileBind/mobileBind?refid=1626229326`,
        });
      }
    }else{
      let bindBackUrl = miniJumpAddress || location.href;
      wx.miniProgram.navigateTo({
        url: `/pages/common/mobileBind/mobileBind?refid=1626229326&pageindex=webview_redirect&redirect=${encodeURIComponent(
          bindBackUrl,
        )}`,
      });
      reject();
    }
  })
}

//ifNotDo： 是否执行登录操作
//miniJumpAddress： 微信小程序登录之后跳转的地址，不传默认为当前地址
export const login = (ifNotDo = false, miniJumpAddress) => {
  return new Promise(async (resolve, reject) => {
    if (getUserInfo()) return resolve(getUserInfo());
    if(ifUserMock){
      setUserInfo(userMock)
      return resolve(userMock)
    }
    let env = await getEnv();
    try {
      if (env === 'cbd') {
        setTimeout(() => {
          bridge.userInfoPlugins.login().then((res) => {
            let isLogin = res.isLogin;
            if (isLogin != 1) {
              if (ifNotDo) return resolve(false);
              bridge.naviPlugins.requestLogin().then((res) => {
                if (res.loginResult == 0) {
                  setUserInfo({
                    memberId: res.clientInfo.memberId,
                    deviceId: res.clientInfo.deviceId,
                    platId: res.osType === 'android' ? 10 : 11,
                  });
                  return resolve(getUserInfo());
                } else reject();
              });
            } else {
              bridge.userInfoPlugins.getSystemInfo().then((res) => {
                let MemberId = res.clientInfo.memberId;
                // let MemberId = 'f272e81efc88a87191f79831af39587e'
                setUserInfo({
                  memberId: MemberId,
                  deviceId: res.clientInfo.deviceId,
                  platId: res.osType === 'android' ? 10 : 11,
                });
                return resolve(getUserInfo());
              });
            }
          });
        }, 100);
      } else if (env === 'mini') {
        let isbind = getUrlParam('isbind') || '';
        let sessionCode = getUrlParam('sessionCode') || '';
        if (isbind == '1' && sessionCode) {
          setUserInfo({ sessionCode, platId: 4 });
          return resolve(getUserInfo());
        }
        if (ifNotDo) return resolve(false);
        wxMiniLogin(miniJumpAddress).then(res => {
          setUserInfo({ sessionCode: res.sessionCode, platId: 4 });
          resolve(getUserInfo());
        }).catch(rej => {
          reject('wxLoginFail');
        })
      } else {
        Dialog.confirm({
          title: '提示',
          message: '请前往巴士管家app参与活动',
          confirmButtonText: '前往参与',
          cancelButtonText: '取消',
        })
          .then(() => {
            // on confirm
            location.href =
              'https://a.app.qq.com/o/simple.jsp?pkgname=com.chebada';
          })
          .catch(() => {
            // on cancel
          });
        reject();
      }
    } catch (e) {
      reject();
    }
  });
}

//针对微信小程序，强制跳转登录页面
//miniJumpAddress： 微信小程序登录之后跳转的地址，不传默认为当前地址
export const forceLogin = async (miniJumpAddress) => {
  let env = await getEnv();
  if (env === 'cbd') {
    Toast('授权失败，请重新授权~');
  } else if (env === 'mini') {
    await wxMiniLogin(miniJumpAddress)
  }
};

//执行登录操作
//miniJumpAddress： 微信小程序登录之后跳转的地址，不传默认为当前地址
export const doLogin = (miniJumpAddress) => {
  return login(false, miniJumpAddress)
};

//获取登录信息，但不会登录，成功直接返回登录信息，不成功会resolve(false)
export const checkIfLogin = () => {
  return login(true)
}

export const initMiniConnection = async () => {
  let env = await getEnv();
  if(env !== 'mini')return;
  updateMiniParam()
  wasdk.onShow(function (data) {
    updateMiniParam()
  })
  function updateMiniParam(){
    let query = getQuery();
    miniData.param = query;
    if(miniData.store && miniData.store.length){
      miniData.isJumping = false;
      miniData.store.forEach((item) => {
        if(query.isbind == '1' || query.isbind == 'true')item[0] && item[0](query);
        else item[1] && item[1](query);
      });
      miniData.store = [];
    }
  }
}